<?php

namespace App\Http\Controllers\Admins;

use App\Http\Controllers\AdminController;
use App\Http\Controllers\Controller;
use App\Http\Resources\Admins\UserResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class User extends AdminController
{
    public function list(Request $request)
    {
        $elem = \App\Models\User::latest();

        if ($request->filled('search')){

            $search = $request->input('search');

            switch ($search['type']){

                case 'name':
                    $elem->where('name','like','%'.$search['content'].'%');
                    break;
                case 'mobile':
                    $elem->where('mobile','like','%'.$search['content'].'%');
                    break;
                case 'identity':
                    $elem->where('identity','like','%'.$search['content'].'%');
                    break;
            }
        }


        $data = $elem->paginate($request->input('limit',10));

        return $this->ReturnPage(UserResource::collection($data));
    }

    public function listPost(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'id'    => 'required|integer',
            'mobile'=> 'required|integer',
            'nickname'  => 'required',
            'name'      => 'required',
            'identity'  => 'required',
            'address'   => 'required',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        \App\Models\User::find($post['id'])->update($post);

        return $this->ReturnSuccessInfo();
    }

    public function listAdmin(Request $request)
    {
        $validator = Validator::make($post = $request->all(),[
            'id'    => 'required|integer',
            'status'=> 'required|boolean',
        ]);

        if ($validator->fails()){

            return $this->ReturnFailed(1,$validator->errors());
        }

        \App\Models\User::find($post['id'])->update([
            'is_admin'  => $post['status'],
        ]);

        return $this->ReturnSuccessInfo();
    }

}
